# -*- coding:utf-8 -*-
import os
import re
import openpyxl as opxl
import pysvn
import datetime
import getopt
import urllib
import logging
from logging import handlers
import sys, getopt
import shutil
from time import strftime, localtime
import hashlib

localRevision = None
localReplaceRevision = None
localPath = "../../resource"
replacePath ="../../resource1"
needchange = False
needSvnChangeReplaceAllDiff = True
log = None
isFail = False
isNeedReplaceAll = True

class Logger(object):
    level_relations = {
        'debug':logging.DEBUG,
        'info':logging.INFO,
        'warning':logging.WARNING,
        'error':logging.ERROR,
        'crit':logging.CRITICAL
    }#日志级别关系映射

    def __init__(self,filename,level='info',when='D',backCount=3,fmt='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'):
        self.logger = logging.getLogger(filename)
        format_str = logging.Formatter(fmt)#设置日志格式
        self.logger.setLevel(self.level_relations.get(level))#设置日志级别
        sh = logging.StreamHandler()#往屏幕上输出
        sh.setFormatter(format_str) #设置屏幕上显示的格式
        th = handlers.TimedRotatingFileHandler(filename=filename,when=when,backupCount=backCount,encoding='utf-8')#往文件里写入#指定间隔时间自动生成文件的处理器
        #实例化TimedRotatingFileHandler
        #interval是时间间隔，backupCount是备份文件的个数，如果超过这个个数，就会自动删除，when是间隔的时间单位，单位有以下几种：
        # S 秒
        # M 分
        # H 小时、
        # D 天、
        # W 每星期（interval==0时代表星期一）
        # midnight 每天凌晨
        th.setFormatter(format_str)#设置文件里写入的格式
        self.logger.addHandler(sh) #把对象加到logger里
        self.logger.addHandler(th)

def main(argv):
    global log
    global localPath
    global replacePath
    inputfile = ''
    outputfile = ''
    try:
        opts, args = getopt.getopt(argv,"hi:o:",["ifile="])
    except getopt.GetoptError:
        print('test.py -i <inputfile>')
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print ('test.py -i <inputfile> -o <outputfile>')
            sys.exit()
        elif opt in ("-i", "--ifile"):
            inputfile = arg
        elif opt in ("-o", "--ofile"):
            outputfile = arg
    localPath = inputfile
    replacePath = outputfile
    log.logger.info('提取的文件目录为：{}'.format(inputfile))
    log.logger.info('替换的文件目录为：{}'.format(replacePath))

#回调函数，获取登录到svn仓库的用户名和密码 
def get_login( realm, user, may_save ):
    #svn账号
    username = "wangwanjue"
    #svn密码
    password = ""
    return True, username, password, False

def Stamp2Time():      # 将时间戳转换成时间显示格式
    timeArray = localtime()
    print(timeArray)
    Time = strftime("%Y{}%m{}%d{} %H{}%M{}%S{}", timeArray).format('年','月','日','时','分','秒 旧文件副本')
    return Time

def get_python_paths(path='./Files'):
    """
    获取LuaFiles文件夹中所有以.lua||.py为后缀的文件路径
    :param path: 当前传入文件夹路径
    :return: None
    """
    for l in os.listdir(path):
        current_path = path + '/' + l
        if os.path.isfile(current_path):                            # 如果路径为文件，则判断是否以.lua结尾，是的话则放入列表中
            if current_path.endswith('.py') and (not current_path.endswith('/badword.py')):
                ALL_PYTHON_PATHS.append(current_path)
            elif(current_path.endswith('/badword.py')):
                ALL_MOVE_PATHS.append(current_path)
        else:                                                       # 如果是文件夹，则递归
            get_python_paths(current_path)

def manage_python_files(python_path,excel_chinese_list,add_chinese_list,checkinFilleList,failFilleList):
    """
        打开lua文件
        :param python_path: python文件路径
        :return: None
        """ 
    global needchange
    global isFail
    global needSvnChangeReplaceAllDiff
    needchange = False
    isFail = False
    needSvnChangeReplaceAllDiff = True
    new_fils = ""
    print('该路径{}脚本开始处理>>>>>'.format(python_path))                  # 打印进度
    with open(python_path, 'r') as f:
        new_fils = f.read()
    with open(python_path, 'r') as f:
        new_fils = write_chinese(f.readlines(),new_fils,excel_chinese_list)
    if (needchange or needSvnChangeReplaceAllDiff ) or isNeedReplaceAll:
        fullPath = python_path.replace(localPath,replacePath)
        checkinFilleList.append(fullPath)
        dirPath = fullPath[0:fullPath.rfind("/")]
        if not os.path.exists(dirPath):
            os.makedirs(dirPath)
        print('该路径{}脚本已经处理完毕'.format(fullPath))           
        with open(fullPath, 'w') as f:              # 
            f.write(new_fils)
            f.close
    if(isFail==True and python_path not in failFilleList):
        failFilleList.append(python_path)
        log.logger.error("{}替换失败".format(python_path))
    print('该路径{}脚本已经处理完毕'.format(python_path))                  # 打印进度

def write_chinese(lines,content,excel_chinese_list):
    """
    获取所有中文字符串
    :param content: lua文件内容
    :return: 所有符合的中文字符串
    """
    addTextlines = ""
    addTextOldlines = ""
    addLine = False
    old_line = ""
    for line in lines:
        # line = re.sub(r'(?:--)(.*?)[\[\[](.*?)[\]\]]','', line)
        old_line = line 
        lineTtpe = CheckSingleLine(OnlyStr(line),addLine)
        if(lineTtpe==1): # 注释不需要提取
            addTextlines = ""
            addTextOldlines = ""
            addLine = False	
        elif(lineTtpe==2):# ]]结束需要提取		
            addLine = False
            addTextlines += line
            # content = write_chineseNLines(addTextlines,content,excel_chinese_list)         
            addTextlines = ""
        elif(lineTtpe==3):# [[开始需要相加行
            addLine = True
            addTextlines += line 
            addTextOldlines += old_line        	
        elif(lineTtpe==4):# “”‘’需要提取
            addTextlines = ""
            addTextOldlines = ""
            addLine = False	
            content = write_chineseOneLine(line,content,excel_chinese_list,old_line)										
        else:
            addTextlines = ""
            addLine = False						
    return content  

def write_chineseNLines(content,contentFill,excel_chinese_list,old_line):
    """
    获取所有中文字符串
    :param content: lua文件内容
    :return: 所有符合的中文字符串
    """
    replace_content = old_line
    old_content = old_line
    keys ={}
    keyItems = []
    all_result1 = re.findall(r'\[\[(?:.|\r|\n)*?\]\]', content)                        # 首先提取所有双引号内的字符
    for a in all_result1:
        if re.search(r'[\u4e00-\u9fa5]+', a):                        # 判断双引号内是否有中文
            if a.count('[[') > 1:                                     # 此处判断为排除"ComposePage", "合成产物无效"这种情况
                judge = a.split('[[')                                 # 将上述情况的字符串根据"分割并再做判断
                for j in judge:
                    if re.search(r'[\u4e00-\u9fa5]+', j):
                        b=j.replace('[[', '')
                        c=b.replace(']]', '')
                        info=replace_keyToText(keys,c,excel_chinese_list,keyItems)
                        keys = info[0]
                        keyItems = info[1]
            else:
                b=a.replace('[[', '')
                c=b.replace(']]', '')
                info=replace_keyToText(keys,c,excel_chinese_list,keyItems)
                keys = info[0]
                keyItems = info[1]
    keyItems.sort(key = lambda i:len(i),reverse=True) 
    for keyplace in keyItems:
        replace_content = replace_content.replace(keyplace,keys[keyplace])
    # print('----->{}脚本开始处理后>>>>>'.format(contentFill1)) 
    contentFill = contentFill.replace(old_content,replace_content) 
    return contentFill

def IF_ELSE(bStatement ,X,Y):
    if(bStatement):
        return X
    else:
        return Y

def get_LineAllConnectNew(content,needTextList):
    print("------->>>>{}".format(content))
    isYinghaonei = False
    isBegin = True
    dianCount = 0
    word = ""  
    words =[]
    newords = {} 
    index = 0
    find = 0
    isNeedAdd = 0
    for iword in content:
        if((iword=='"'or iword=="'") and isBegin == True):
            isNeedAdd = 1
            isYinghaonei = IF_ELSE(isYinghaonei == True, False, True)
        if(isBegin == True  ):
            if(isYinghaonei==False and iword =="+"):
                dianCount=dianCount+1
                if(dianCount==1):
                    dianCount =0
                    isNeedAdd = 1
                    find = 1
            else:
                # if(dianCount==1):
                #     word = word + "+"
                #     word = word + iword
                #     dianCount = 0
                # else:
                if (isYinghaonei == False and iword ==" " ):
                    word = word
                else:
                    if(isNeedAdd == 1 and isYinghaonei==True):
                        word = word
                    else:    
                        word = word + iword              
        if((iword =="\n" or isNeedAdd == 1) and isBegin == True ):           
            if (word !=""):
                words.append(word)
            word = ""  
            if(len(words)>0):
                index = index +1
                newords[index] = words
                words=[]
            if(iword =="\n"):
                isBegin = False
            if(isNeedAdd == 1 and isYinghaonei==True):
                word = iword    
            dianCount = 0
            isNeedAdd = 0
            continue 
    chineseKey = ""  
    if(find>0):         
        for i,value in newords.items():
            print("------->>>>{}".format(value)) 
            for iword in value:      
                if(iword.count('"') > 1 or iword.count("'")>1):
                    content = content.replace(iword,"")
                    tem = iword.replace("'","")
                    tem = tem.replace('"',"")
                    chineseKey = chineseKey + tem              
                else:
                    chineseKey = chineseKey +"{}"              
                    content = content.replace(iword,"")
        if(chineseKey!=""):
            needTextList.append(chineseKey)
    return content

def replace_richText(content):
    print(' 富文本处理content是：{}'.format(content))
    allRichText = re.findall(r'#A|#R|#D&|#H&|#r|%s|%d|@N|\$SRV|\$P|\$I|\$N|\$O|\$M|\$p1|\$p2|\$FROM|\$TO|%:m|%:g|%:w|%:s|%:t|!:m|!:g|!:w|!:s|!:t|\$[GW][0-9]+|#E[0-9]+&|#F[0-9]+&|#C[0-9]+&|#[0-9]+|#P[0-9]+&', content)
    print(' 富文本处理allRichText是：{}'.format(allRichText))
    index = 0
    for a in allRichText:
        index = index+1
        print(' 富文本处理{}'.format(a))
        content = content.replace(a,"<{}>".format(index))
    # allRichText = re.findall(r'\$.+\$', content)
    # print(' 富文本处理allRichText是：{}'.format(allRichText))
    # for a in allRichText:
    #     index = index+1
    #     print(' 富文本处理{}'.format(a))
    #     content = content.replace(a,"<{}>".format(index))
    return content
def replace_keyToText(replace_keys,key,excel_chinese_list,keyItems):
    global log
    global needchange
    global isFail
    newKey = replace_richText(key)
    if(OnlyStr(newKey) in excel_chinese_list):
        newWord = excel_chinese_list[OnlyStr(newKey)][2]
        # allRichText = re.findall(r'#A|#R|#D&|#H&|#r|%s|%d|@N|\$SRV|\$P|\$I|\$N|\$O|\$M|\$p1|\$p2|\$FROM|\$TO|\$门派第一高手|%:m|%:g|%:w|%:s|%:t|!:m|!:g|!:w|!:s|!:t|\$[GW][0-9]+|#E[0-9]+&|#F[0-9]+&|#C[0-9]+&|#[0-9]+|#P[0-9]+&', key)
        allRichText = re.findall(r'#A|#R|#D&|#H&|#r|%s|%d|@N|\$SRV|\$P|\$I|\$N|\$O|\$M|\$p1|\$p2|\$FROM|\$TO|%:m|%:g|%:w|%:s|%:t|!:m|!:g|!:w|!:s|!:t|\$[GW][0-9]+|#E[0-9]+&|#F[0-9]+&|#C[0-9]+&|#[0-9]+|#P[0-9]+&', key)
        index = 0
        nowKey = key
        for a in allRichText:
            index = index+1
            newWord = newWord.replace("<{}>".format(index),a)
            nowKey = nowKey.replace(a,"<{}>".format(index))
        # allRichText = re.findall(r'\$.+\$', nowKey)
        # for a in allRichText:
        #     index = index+1
        #     newWord = newWord.replace("<{}>".format(index),a)
        judge2 = newWord.split("{}")
        judge1 = key.split("{}")
        index = 0
        newJudge2 =[]
        newJudge1 =[]
        for j in judge2:
            if(OnlyStr(j)!=""and re.search(r'[\u4e00-\u9fa5]+', j)):
                newJudge2.append(j)
        for j in judge1:
            if(OnlyStr(j)!=""and re.search(r'[\u4e00-\u9fa5]+', j)):
                newJudge1.append(j)
        if(len(newJudge1)==len(newJudge2)):
            for j in newJudge2:
                index = index+1
                if(OnlyStr(j)!=""):
                    if(newJudge1[index-1] not in replace_keys):
                        replace_keys[newJudge1[index-1]] = j
                        keyItems.append(newJudge1[index-1]) 
                    needchange = True
        else:
            isFail = True
            log.logger.error("{}替换失败".format(key))
    else:
        isFail = True
        log.logger.error("{}替换失败".format(key))
    return [replace_keys,keyItems]

def IsPassLine(strLine):
    # 是否是可以忽略的行
    # 可忽略行的正则表达式列表
    RegularExpressions = ["""\'.*#.*\'""", """\".*#.*\"""","""\'\'\'.*#.*\'\'\'""", """\"\"\".*#.*\"\"\""""]
    for One in RegularExpressions:
        zz = re.compile(One)
        if re.search(zz, strLine) == None:
            continue
        else:
            return True  # 有匹配 则忽略
    return False

def get_findzhushi(content):
    index = content.find('#')  # 获取带注释句‘#’的位置索引
    NewStr = ""
    if index == -1  or IsPassLine(content):
        if content.strip() != '':  # 排除纯空的行
            NewStr =  content
    else:
        NewStr = content
        if index != 0:
            NewStr = content[:index] + '/n'  # 截取后面的注释部分
    return NewStr

def write_chineseOneLine(content,contentflils,excel_chinese_list,old_line):
    """   
    """ 
    global log
    old_content =  old_line
    replace_content =old_line      
    content = get_findzhushi(content)
    content = re.sub(r'(?:print).*[\'\"].+[\'\"].*[\)]','', content)  
    content = content.replace('\\"','<T>')      
    all_result1 = re.findall(r'(?:=)(.*[\+].+){1}(?=[\,|\;|\n])', content)              # 
    needTextList = []
    keys = {}
    keyItems = []
    if(len(all_result1)):
        content = get_LineAllConnectNew(content,needTextList)
        for a in needTextList:
            if re.search(r'[\u4e00-\u9fa5]+', a) :                    
                info =replace_keyToText(keys,a,excel_chinese_list,keyItems)
                keys = info[0]
                keyItems = info[1]
    needTextList = []
    all_result2 = re.findall(r'(?:\()(.*[\+].+){1}(?=[,|\)])', content) 
    if(len(all_result2)):
        content = get_LineAllConnectNew(content,needTextList)
        for a in needTextList:
            if re.search(r'[\u4e00-\u9fa5]+', a) :                    
                info=replace_keyToText(keys,a,excel_chinese_list,keyItems)
                keys = info[0]
                keyItems = info[1]
    
    all_result = re.findall(r'[\'\"](.*?)[\'\"]', content)               
    for a in all_result:
        if re.search(r'[\u4e00-\u9fa5]+', a) :                        
            if a.count('"') > 2:                                      
                judge = a.split('"')                                 
                for j in judge:
                    j=j.replace('"',"")
                    if re.search(r'[\u4e00-\u9fa5]+', j):
                        info=replace_keyToText(keys,j,excel_chinese_list,keyItems)
                        keys = info[0]
                        keyItems = info[1]
            elif a.count("'") > 2:                                  
                judge = a.split("'")                                 
                for j in judge:
                    j=j.replace("'","")
                    if re.search(r'[\u4e00-\u9fa5]+', j):
                        info=replace_keyToText(keys,j,excel_chinese_list,keyItems)
                        keys = info[0]
                        keyItems = info[1]
            else:
                a=a.replace("'","")
                a=a.replace('"',"")
                info=replace_keyToText(keys,a,excel_chinese_list,keyItems)
                keys = info[0]
                keyItems = info[1]
    keyItems.sort(key = lambda i:len(i),reverse=True) 
    for keyplace in keyItems:
        log.logger.info("------->>>>{}_____{}".format(keyplace,keys[keyplace]))
        keyplace_new = keyplace.replace('<T>','\\"') 
        replace_new = keys[keyplace].replace('<T>','\\"') 
        replace_content = replace_content.replace(keyplace_new,replace_new)
    log.logger.info("------->>>>{}_____{}".format(old_content,replace_content))
    contentflils = contentflils.replace(old_content,replace_content)
    return contentflils

def write_chineseOne_(content,contentflils,excel_chinese_list,old_line):
    old_content =  old_line
    replace_content =old_line 
    keys = {}
    keyItems = []
    all_result = re.findall(r'[\'\"].+[\'\"]', content)              # 
    for a in all_result:
        if re.search(r'[\u4e00-\u9fa5]+', a) :                        # 
            if a.count('"') > 2:                                     # 
                judge = a.split('"')                                 # 
                for j in judge:
                    j=j.replace('"',"")
                    if re.search(r'[\u4e00-\u9fa5]+', j):
                        info=replace_keyToText(keys,j,excel_chinese_list,keyItems)
                        keys = info[0]
                        keyItems = info[1]
            elif a.count("'") > 2:                                  # 
                judge = a.split("'")                                 # 
                for j in judge:
                    j=j.replace("'","")
                    if re.search(r'[\u4e00-\u9fa5]+', j):
                        info=replace_keyToText(keys,j,excel_chinese_list,keyItems)
                        keys = info[0]
                        keyItems = info[1]
            else:
                a=a.replace("'","")
                a=a.replace('"',"")
                info=replace_keyToText(keys,a,excel_chinese_list,keyItems)
                keys = info[0]
                keyItems = info[1]
    for keyplace in keyItems:
        replace_content = replace_content.replace(keyplace,keys[keyplace])
    contentflils = contentflils.replace(old_content,replace_content)
    return contentflils

def OnlyStr(tmp_str):
    if(tmp_str == None):
        return None
    return tmp_str.strip("\r\n").strip("\n").strip("\t").strip()

#检查单独一行
def CheckSingleLine(str_line,isAddLine):
    if(isAddLine):
        zh_match = re.match(r'.*[\"\"\"|\'\'\'].*', str_line)
        if zh_match:
            return 2
        return 3
    else:	
        if "#" == str_line[:1]:
            return 1
        else:
            zh_match = re.search(r'\"\"\"|\'\'\'', str_line)
            if(zh_match):
                zh_match = re.search(r'\"\"\"|\'\'\'', str_line)
                if(zh_match):
                    return 2    
                return 3			
            zh_match = re.search(r'.*[\'\"].*[\u4e00-\u9fa5]+.*[\'\"].*', str_line)
            if(zh_match):
                return 4
            return 5

def get_excel_chinese():
    """
    获取excel表中第一列的全部内容，用于后续比较是否重复
    :return: excel文件第一列的所有文本
    """
    excel_chinese_list = {}
    fail_list = []
    pathName = 'translation.xlsx'
    pathName2 = 'translationCompleted.xlsx'
    wb =None
    if(os.path.isfile(pathName2)):
        wb = opxl.load_workbook(pathName2)
        ws = wb.active
        ws = wb['content']
        ws3 = wb['revisionSever']
        ws4 = wb['replaceRevisionSever']
        ws5 = wb['failFillsSever']
    else:
        wb = opxl.Workbook()
        ws = wb.active
        ws.title = 'content'
        ws3 = wb.create_sheet('revisionSever')
        ws4 = wb.create_sheet('replaceRevisionSever')
        ws5 = wb.create_sheet('failFillsSever')
        wb.save(pathName2)
    if(os.path.isfile(pathName)):
        wb2 = opxl.load_workbook(pathName)
        ws2 = wb2.active
        ws2 = wb2['updateContent']
    else:
        wb2 = opxl.Workbook()
        ws2 = wb2.active
        ws2.title = 'updateContent'
        wb2.save(pathName)
    for rx in range(2, ws.max_row + 1):
        temp_list = []
        w1 = ws.cell(row=rx, column=1).value      
        w2 = ws.cell(row=rx, column=2).value
        w3 = ws.cell(row=rx, column=3).value
        print('开始读入>>>>>{}-----{}------{}--{}'.format(rx,w1,w2,w3))
        temp_list = [w1,w2,w3]
        excel_chinese_list[OnlyStr(w2)] = temp_list
    for rx in range(1, ws.max_row+1):
        w1 = ws5.cell(row=rx, column=1).value      
        fail_list.append(w1)
    revision1 = ws3.cell(row=1, column=1).value
    revision2 = ws4.cell(row=1, column=1).value
    return [excel_chinese_list,fail_list,revision1,revision2]


def write_excel(failFilleList):
    """
    将内容写到translation.xlsx中 
    :param chinese_list: 要写的中文字符串列表
    :return: None
    """
    wb = opxl.load_workbook('translationCompleted.xlsx')
    ws3 = wb['revisionSever']
    ws4 = wb['replaceRevisionSever']
    cell_num1 = 'A{}'.format(1)
    ws3[cell_num1] = localRevision
    ws4[cell_num1] = localReplaceRevision
    del wb['failFillsSever']
    ws5 = wb.create_sheet('failFillsSever')
    index = 1
    for key in failFilleList:
        cell_num1 = 'A{}'.format(index)
        ws5[cell_num1] = key
        index += 1    
    wb.save('translationCompleted.xlsx')

def findDiff(localrevision,replacerevision):
    global log
    new_diff_list = []
    revision_min = None
    revision_max = None
    old_revision = replacerevision
    new_revision = None
    client = pysvn.Client()
    #登陆到svn
    client.callback_get_login = get_login
    entry = client.info(localPath)
    new_revision =  entry.commit_revision.number
    print('最新版本:{}'.format(new_revision))
    if new_revision != localrevision:
        log.logger.error("提取和替换版本不一致提取版本{}，当前版本{}".format(localrevision,new_revision))
        return [ALL_PYTHON_PATHS,replacerevision,False]
    
    #开始的版本号
    if old_revision == None:
        revision_min = pysvn.Revision( pysvn.opt_revision_kind.base )
    else:
        revision_min = pysvn.Revision( pysvn.opt_revision_kind.number, int(old_revision))
    #获取svn目前的版本号
    if new_revision == None:
        revision_max = pysvn.Revision( pysvn.opt_revision_kind.head )
    else:
        revision_max = pysvn.Revision( pysvn.opt_revision_kind.number, int(new_revision))
    
    print('最新版本:{}'.format(revision_max))
    #获取svn之前的版本号
    if old_revision != None:
        #获取两个版本之间改动的文件列表
        summary = client.diff_summarize(localPath,revision_min,localPath,revision_max)
        filePythonList = []
        for changed in summary:
            #手动删除掉已经删除但还存留的垃圾文件  
            fullPath = ""
            if pysvn.diff_summarize_kind.delete == changed['summarize_kind']:
                fullPath = localPath+"/"+changed['path']
                targetFile = fullPath.replace(localPath,replacePath) 
                print('删除:{}'.format(targetFile))  
                if os.path.exists(targetFile):
                    if os.path.isfile(targetFile):
                        # 创建副本
                        suffix = targetFile.split('.')[-1]  # 得到文件的后缀名
                        B_copy_path = targetFile[:-len(suffix)-1]+"(%s)."%(Stamp2Time())+suffix
                        print ('[副本]\t{} ===> {}'.format(targetFile,B_copy_path))
                        shutil.copy2(targetFile,B_copy_path)
                        os.remove(targetFile)
            #获取两个版本之间修改的和新增的文件
            if  pysvn.diff_summarize_kind.added == changed['summarize_kind'] or pysvn.diff_summarize_kind.modified == changed['summarize_kind']:
                print(changed['summarize_kind'], changed['path'])
                if changed['node_kind'] == pysvn.node_kind.file:
                    # print(svnurl+"/"+changed['path'])
                    # file_text = client.cat(svnurl+"/"+changed['path'], revision_max) 
                    if pysvn.diff_summarize_kind.added == changed['summarize_kind']:
                        fullPath = localPath+changed['path']
                    else:
                        fullPath = localPath+changed['path']       
                    if(fullPath.endswith('.py')):
                        # print(svnurl+"/"+changed['path'])
                        filePythonList.append(fullPath)

    if old_revision !=None:
        print('SVN路径:{}'.format(entry.url))
        print('最新版本:{}'.format(entry.commit_revision.number))
        print('提交人员:{}'.format(entry.commit_author))
        print('更新日期:{}'.format( datetime.datetime.fromtimestamp(entry.commit_time)))
        # write_excel(new_chinese_list)
        print('处理>>>>>1{}'.format([filePythonList,new_revision]))
        return [filePythonList,new_revision,True]
    else:
        entry = client.info(localPath)
        print('SVN路径:{}'.format(entry.url))
        print('最新版本:{}'.format(entry.commit_revision.number))
        print('提交人员:{}'.format(entry.commit_author))
        print('更新日期:{}'.format( datetime.datetime.fromtimestamp(entry.commit_time)))
        # write_excel(new_chinese_list)
        new_revision =  entry.commit_revision.number
        get_python_paths(localPath)
        # print('处理>>>>>2{}'.format([1,new_revision]))
        return [ALL_PYTHON_PATHS,new_revision,True]
    return [ALL_PYTHON_PATHS,replacerevision,False]

def checkinDiff(revision,filleList):
    global log
    client = pysvn.Client()
    #登陆到svn
    client.callback_get_login = get_login
    log.logger.info(filleList)

    # checkAdd(filleList)
    # changes = client.status('./examples/pysvn')
    # for f in changes:
    #     if f.text_status == pysvn.wc_status_kind.added:
    #         client.add(localPath+)
    # client.checkin(filleList, 'by translation code')
def checkAdd(filles):
    global log
    client = pysvn.Client()
    #登陆到svn
    # client.callback_get_login = get_login
    log.logger.info(filles)
    for key in filles:
        info = client.info(key)
        log.logger.info(key)
        if info == None:
            client.add(key)
if __name__ == '__main__':
    dirPath = "config_log"
    if not os.path.exists(dirPath):
        os.makedirs(dirPath)
    log = Logger('config_log/write_chinese_log.log',level='debug')
    Logger('config_log/write_chinese_log_error.log', level='error').logger.error('error')
    main(sys.argv[1:])
    ALL_LUA_PATHS = []
    ALL_PYTHON_PATHS = []
    ALL_MOVE_PATHS = []
    checkinFilleList = []
    failFilleList = []  
    old_chinese_list = {}#中文key
    new_chinese_list = {}
    info=get_excel_chinese()
    old_chinese_list = info[0]
    failFilleList  = info[1]
    localRevision = info[2]
    localReplaceRevision = info[3]
    print('处理>>>>>333333{}'.format([localRevision,localReplaceRevision]))
    if localRevision != None:
        print('处理>>>>>111122222{}'.format([localRevision,localReplaceRevision]))
        info = findDiff(localRevision,localReplaceRevision)
        ALL_PYTHON_PATHS = info[0]
        replaceRevision = info[1]
        isSucceed = info[2]

        if isSucceed ==True:
            for fullPath in failFilleList:
                if(fullPath!= None):
                    if(fullPath.endswith('.py') and fullPath not in ALL_LUA_PATHS):
                        ALL_PYTHON_PATHS.append(fullPath)
            failFilleList = []
            for py_path in ALL_PYTHON_PATHS:
                manage_python_files(py_path,old_chinese_list,new_chinese_list,checkinFilleList,failFilleList)
            for py_path in ALL_MOVE_PATHS:
                targetFile = py_path.replace(localPath,replacePath)
                shutil.copy2(py_path,targetFile)
            localReplaceRevision = replaceRevision
            write_excel(failFilleList)
            # checkinFilleList.append(localPath+'tool_res/get_chinese_po/translationCompleted.xlsx')
            # checkinDiff(localRevision,checkinFilleList)
            log.logger.info("提取版本{},当前版本{}".format(localRevision,localReplaceRevision))
        else:
            log.logger.error("替换版本文件与提取不一致替换失败")
    else:
        log.logger.error("本地文件svn版本不存在")
    
